package com.idc.common.log;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * @author chenbingbing
 */
public class LogIpConfig extends ClassicConverter {

	private static final String NONE = "";

	public static String getRemoteRealIp() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (null == requestAttributes) {
			return NONE;
		}
		HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		if (null == request) {
			return NONE;
		}
		try {
			String remoteAddr = request.getRemoteAddr();
			String forwarded = request.getHeader("X-Forwarded-For");
			String realIp = request.getHeader("X-Real-IP");
			if (!StringUtils.isEmpty(forwarded) && !"unknown".equalsIgnoreCase(forwarded)) {
				return forwarded.split(",")[0];
			}
			if (!StringUtils.isEmpty(realIp) && !"unknown".equalsIgnoreCase(realIp)) {
				return realIp;
			}
			return remoteAddr;
		} catch (Exception e) {
			return NONE;
		}
	}

	@Override
	public String convert(ILoggingEvent event) {
		return getRemoteRealIp();
	}

}
